import type { Ref } from 'vue'
import { ref } from 'vue'
import { useRequest } from 'ahooks-vue'
import type { PageParams, PageResponse } from '@/utils/request'

export default function<T>(run: <U>(...args: any[]) => Promise<PageResponse<U>> | (<U>(...args: any) => Promise<PageResponse<U>>)) {
  const total = ref(0)
  const data: Ref<T[]> = ref([])
  const { run: doQuery, loading } = useRequest(run<T>, { manual: true })
  const handleQuery = async (params: Record<string, any> & PageParams) => {
    const { rows, total: count } = (await doQuery(params))!
    total.value = count
    data.value = rows
  }

  return {
    total,
    data,
    loading,
    handleQuery,
  }
}
